package net.wangds.dymodel.utls;

import net.wangds.dymodel.meta.entity.DyModelDefEntity;
import net.wangds.dymodel.meta.entity.DyModelPropDefEntity;
import net.wangds.log.helper.LogHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2021/2/16 2:48.
 */
public class DynamicModelUtils {

    public static String buildFullTextIndexName(DyModelDefEntity model){
        return "IDX_FT_"+model.getTablename();
    }


    public static  String toColumnName(DyModelPropDefEntity def){
        return "`"+def.getColumnName()+"`";
    }


    public static String toFullTableName(DyModelDefEntity model){
        String schema = model.getSchema();
        schema = StringUtils.isBlank(schema)?"":schema;
        return schema+
                (StringUtils.isEmpty(schema) ? "" : ".") +
                StringUtils.trim(model.getTablename());
    }

    public static Object fetchFieldVal(Object model, DyModelPropDefEntity field){
        return fetchFieldVal(model, field.getNameEn());
    }

    public static Object fetchFieldVal(Object model, String fieldName){
        if(model instanceof Map){
            return ((Map<?, ?>)model).get(fieldName);
        } else {
            PropertyDescriptor prop = BeanUtils.getPropertyDescriptor(model.getClass(), fieldName);
            if(prop==null){
                return null;
            }
            Method method = prop.getReadMethod();
            if(method==null){
                return null;
            }

            try {
                return method.invoke(model);
            } catch (IllegalAccessException|InvocationTargetException e) {
                LogHelper.warn(e);
            }
            return null;
        }
    }

}
